package xc.com.freemarker.service.impl;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import xc.com.freemarker.service.GridFsService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Service
public class GridFsServiceImpl implements GridFsService {
    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private GridFSBucket gridFSBucket;
    @Override
    public String queryFile(String id) {
        //根据id查询文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        //打开下载流对象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource，用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFSDownloadStream);
        //抛异常
        try {
            //获取流中的数据
            String string = IOUtils.toString(gridFsResource.getInputStream());
            return string;
        } catch (IOException e) {
            e.printStackTrace();
        }
      return null;
    }

    @Override
    public String addGridFs(File file, String url) {
        //定义输入流
        FileInputStream inputStram = null;
        try {
            inputStram = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //向GridFS存储文件
        ObjectId objectId = gridFsTemplate.store(inputStram, url, "");
        //得到文件ID
        String fileId = objectId.toString();
        return fileId;
    }

    @Override
    public void deleteGridFs(String gId) {
        //根据文件id删除fs.files和fs.chunks中的记录
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(gId)));
    }
}
